package pe.gob.onp.util;

import java.io.Serializable;
import java.util.AbstractList;
import java.util.Iterator;
import java.util.List;

public class LazyLoadingList extends AbstractList implements Serializable {

	 private static final long serialVersionUID = -3229282717958140661L;
	 
	 private LazyLoadable lazyObject;

	 private List firstList;
	 private List viewList;

	 private int currentPage = -1;
	 private int numResults;
	 private int pageSize;
	 private int hashCode = 0;

	 public LazyLoadingList(LazyLoadable lazyObject, int pageSize) {
	   this.lazyObject = lazyObject;
	   this.numResults = lazyObject.getSize().intValue();
	   this.pageSize = pageSize;
	 }
	 
	 
	 public Object get(int i) { 
		 if (i < pageSize) { 
			 if (firstList == null)
				 try {
					 System.out.println("> Se vuelve a consultar la base para index " + i + " y pageSize " + pageSize);
					 firstList = lazyObject.getUpdatedList(i, pageSize);
					 System.out.println(">> Nueva Lista.size = " +  firstList.size());
				 } catch (Exception e) {
					 // TODO Auto-generated catch block
					 e.printStackTrace();
				 } 
				 return firstList.get(i); 
		 } 
		 int page = i / pageSize; 
		 if (page != currentPage) { 
			 currentPage = page; 
			 try {
				 viewList = lazyObject.getUpdatedList(i, pageSize);
			 } catch (Exception e) {
				 // TODO Auto-generated catch block
				 e.printStackTrace();
			 } 
		 }
		 return viewList.get(i % pageSize); 
	 }

	 
	 public int size() {
	   //System.out.println("size: " + numResults);
	   return numResults;
	 }

	 
	 public int hashCode() {
	   if (hashCode == 0){
	     double value = Math.random();
	     String s = String.valueOf(value);
	     s = s.replaceAll("\\.", "");
	     hashCode = Integer.parseInt(s.substring(0, 6));
	   }
	   return hashCode;
	 }

	 
	 public boolean equals(Object o) {
	   if (o == null)
	     return false;
	   return hashCode() == o.hashCode();
	 }

	 
	 public Iterator iterator() {
	   System.out.println("iterator");
	   if (viewList == null && numResults > 0){
	     get(0);
	   }
	   if (viewList != null)
	     return viewList.iterator();
	   return viewList.iterator();
	 }

	 public void setNumResults(int numResults) {
	   this.numResults = numResults;
	 }

	 public void reset(){
	   viewList = null;
	   currentPage = -1;
	   numResults = 0;
	   numResults = lazyObject.getSize().intValue();
	 }

	 public void reload(){
	   reset();
	   get(0);
	 }

	 public void clear() {
	   reset();
	 }

	 public LazyLoadable getLazyObject() {
	   return lazyObject;
	 }

	 public void setLazyObject(LazyLoadable lazyObject) {
	   this.lazyObject = lazyObject;
	 }

	 public List getViewList() {
	   return viewList;
	 }

	 public void setViewList(List viewList) {
	   this.viewList = viewList;
	 }

	}

